package cn.smbms.controller;

    import cn.smbms.pojo.Role;
    import cn.smbms.pojo.User;
    import cn.smbms.service.role.RoleService;
    import cn.smbms.service.role.RoleServiceImpl;
    import cn.smbms.service.user.UserService;
    import cn.smbms.service.user.UserServiceImpl;
    import cn.smbms.tools.Constants;
    import cn.smbms.tools.PageSupport;
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import org.apache.commons.io.FilenameUtils;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import javax.validation.Valid;
    import java.io.File;
    import java.io.IOException;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
   private UserService userService;
    @Autowired
    private RoleService roleService;
    @RequestMapping("/dologin")
    public String doLogin(String userCode, String userPassword, HttpSession session, HttpServletRequest request){
        User user=userService.login(userCode,userPassword);
        if(null != user){//登录成功
            //放入session
            session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转（frame.jsp）
            return "redirect:/user/sys/main.html";
        }else{




            //页面跳转（login.jsp）带出提示信息--转发
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
            // throw  new RuntimeException("用户名或密码错误");
        }
    }
    @RequestMapping("/sys/main.html")
    public String toframe(){
        return "frame";
    }
    @RequestMapping("/login.html")
    public String tologin(){
        return "login";
    }
    /* @ExceptionHandler(value={RuntimeException.class})
     public String doException(RuntimeException e,HttpServletRequest request){
         request.setAttribute("e",e);
         return "error";
     }*/
    @RequestMapping("/query")
    public String query(String queryname,Integer queryUserRole,Integer pageIndex,HttpServletRequest request){
        //查询用户列表
        //int queryUserRole1 = 0;
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if(null!=pageIndex){
            currentPageNo=pageIndex;
        }
        if(null==queryUserRole){
            queryUserRole=0;
        }
        /**
         * http://localhost:8090/SMBMS/userlist.do
         * ----queryUserName --NULL
         * http://localhost:8090/SMBMS/userlist.do?queryname=
         * --queryUserName ---""
         */
        System.out.println("queryUserName servlet--------"+queryname);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);
        if(null==queryname){
            queryname = "";
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryname,queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }


        userList = userService.getUserList(queryname,queryUserRole,currentPageNo, pageSize);
        request.setAttribute("userList", userList);
        List<Role> roleList = null;

        roleList = roleService.getRoleList();
        //条件回显
        request.setAttribute("roleList", roleList);
        request.setAttribute("queryUserName", queryname);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("currentPageNo", currentPageNo);

        return "userlist";
    }

    /**
     * 跳转到添加页面
     * @return
     */
    @RequestMapping(value="/useradd.html",method = RequestMethod.GET)
    public String useradd(@ModelAttribute("user") User user){
        return "useradd";
    }

    /**
     * 添加操作
     * @param user
     * @return
     */
    @RequestMapping(value="useraddsave.html",method = RequestMethod.POST)
    public String useraddSave(User user, HttpSession session,HttpServletRequest request, @RequestParam(value = "attachs",required = false) MultipartFile[] multipartFiles){

        String idPicPath="";
        String workPicPath="";
        String errorInfo="";
        for(int i=0;i<multipartFiles.length;i++){
            MultipartFile multipartFile=multipartFiles[i];
            if(!multipartFile.isEmpty()){
                if(i==0){
                    errorInfo="uploadFileError";
                }else if(i==1){
                    errorInfo="uploadWpError";
                }
                //上传前的准备工作
                //1、定义上传的目标路径
                String path=session.getServletContext().getRealPath("statics"+ File.separator+"uploadfile");
                //2、获取源文件名
                String oldname=multipartFile.getOriginalFilename();
                //3、文件的后缀
                String suffix= FilenameUtils.getExtension(oldname);
                if(multipartFile.getSize()>5000000){
                    request.setAttribute(errorInfo,"文件的大小不能超过5M");
                    return "useradd";
                }else if(suffix.equalsIgnoreCase("jpg")||
                        suffix.equalsIgnoreCase("png")||
                        suffix.equalsIgnoreCase("jpeg")||
                        suffix.equalsIgnoreCase("pneg")){
                    //给文件起新名字
                    String filename = System.currentTimeMillis() + "." + suffix;
                    //创建目标文件
                    File newFile=new File(path,filename);
                    if(!newFile.exists()){
                        newFile.mkdirs();
                    }
                    //写入
                    try {
                        multipartFile.transferTo(newFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo,"上传失败");
                        return "useradd";
                    }
                    if(i==0){

                        idPicPath=filename;
                    }else if(i==1){
                        workPicPath=filename;
                    }

                }else{
                    request.setAttribute(errorInfo,"上传失败");
                    return "useradd";
                }
            }
        }
        user.setWorkPicPath(workPicPath);
        user.setIdPicPath(idPicPath);
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if(userService.add(user)){
            return "redirect:/user/query";
        }else{
            return "useradd";
        }
    }
    @RequestMapping("/tomodify")
    public String tomodify(String userid, Model model){
        User user= userService.getUserById(userid);
        model.addAttribute("user",user);
        return "usermodify";

    }
    @RequestMapping("/modifysave")
    public String modifysave(User user,HttpSession session){
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        if(userService.modify(user)){
            return "redirect:/user/query";
        }else{
            return "usermodify";
        }
    }
    @RequestMapping(value="/view/{id}",method = RequestMethod.GET)
    public String view(@PathVariable String id, Model model){
        User user=userService.getUserById(id);
        model.addAttribute("user",user);
        return "userview";
    }
    @RequestMapping("/ucexist")
    @ResponseBody
    public Object  ucexist(String userCode){
        User user=userService.selectUserCodeExist(userCode);
        Map<String,String> map=new HashMap<String,String>();
        if(null!=user){
            map.put("userCode","exist");
        }else{
            map.put("userCode","noexist");
        }
        return JSONArray.toJSONString(map);
    }
    @RequestMapping(value="/view",method = RequestMethod.GET)
    @ResponseBody
    public User userView(String id){
        User user=null;
        //String userJSON="";
       /*if(null==id||"".equals(id)){
           return "nodata";
       }*/
        try{
            user=userService.getUserById(id);
            //userJSON= JSON.toJSONString(user);
        }catch (Exception e){
            e.printStackTrace();
            //return "failed";
        }
        return user;
    }

}
